package com.rk.hosp.service.impl;
import com.alibaba.fastjson.JSONObject;
import com.rk.hosp.model.hosp.Department;
import com.rk.hosp.repository.DepartmentRepository;
import com.rk.hosp.service.DepartmentService;
import com.rk.hosp.vo.hosp.DepartmentQueryVo;
import com.rk.hosp.vo.hosp.DepartmentVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Example;
import org.springframework.data.domain.ExampleMatcher;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author :Rk.
 * @date : 2022/11/10
 */
@Service
@Slf4j
public class DepartmentServiceImpl implements DepartmentService {

    @Autowired
    private DepartmentRepository departmentRepository;


    /**
     * 保存或者修改科室信息
     * @param paramMap
     */
    @Override
    public void saveOrUpdate(Map<String, Object> paramMap) {
        String jsonStr = JSONObject.toJSONString(paramMap);
        Department department = JSONObject.parseObject(jsonStr, Department.class);

        Department targetDepartment = departmentRepository.getDepartmentByHoscodeAndDepcode(department.getHoscode(), department.getDepcode());
        //如果不存在 就修改
        if(null != targetDepartment) {
            //copy不为null的值，该方法为自定义方法
            //BeanUtils.copyBean(department, targetDepartment, Department.class);
            department.setUpdateTime(targetDepartment.getUpdateTime());
            department.setId(targetDepartment.getId());
            department.setCreateTime(targetDepartment.getCreateTime());
            department.setIsDeleted(targetDepartment.getIsDeleted());
            log.info("===================修改=======================");
            departmentRepository.save(department);
        } else {//如果不存在 就添加
            department.setCreateTime(new Date());
            department.setUpdateTime(new Date());
            department.setIsDeleted(0);
            log.info("===================添加=======================");
            departmentRepository.save(department);
        }
    }

    /**
     * 分页查询科室信息
     * @param page 当前页码
     * @param limit 每页记录数
     * @param departmentQueryVo 查询条件
     * @return
     */
    @Override
    public Page<Department> selectPage(Integer page, Integer limit, DepartmentQueryVo departmentQueryVo) {
        Sort sort = Sort.by(Sort.Direction.DESC, "createTime");
        //0为第一页
        Pageable pageable = PageRequest.of(page-1, limit, sort);

        Department department = new Department();
        BeanUtils.copyProperties(departmentQueryVo, department);
        department.setIsDeleted(0);

        //创建匹配器，即如何使用查询条件
        ExampleMatcher matcher = ExampleMatcher.matching() //构建对象
                .withStringMatcher(ExampleMatcher.StringMatcher.CONTAINING) //改变默认字符串匹配方式：模糊查询
                .withIgnoreCase(true); //改变默认大小写忽略方式：忽略大小写

            //创建实例
        Example<Department> example = Example.of(department, matcher);
        Page<Department> pages = departmentRepository.findAll(example, pageable);

        return pages;

    }

    /**
     * 删除科室信息
     *
     * @param hoscode
     * @param depcode
     */
    @Override
    public void removeDepartment(String hoscode, String depcode) {
        //先根据医院编号和科室编号查询出科室信息
        Department department = departmentRepository.getDepartmentByHoscodeAndDepcode(hoscode, depcode);
        if(department!=null){
            //删除
            departmentRepository.deleteById(department.getId());
        }

    }


    /**
     * 根据医院编号，查询医院所有科室列表
     * @param hoscode
     * @return
     */
    @Override
    public List<DepartmentVo> findDeptTree(String hoscode) {
        //返回的树形结果
        List<DepartmentVo> result=new ArrayList<>();
        //查询出所有科室信息
        List<Department> departList = departmentRepository.getDepartmentByHoscode(hoscode);
        //将科室信息转换为树形结构
        //获取所有的大科室名称
        Map<String, List<Department>> deparmentMap  = departList.stream().collect(Collectors.groupingBy(Department::getBigcode));
        //遍历map结合
        for(Map.Entry<String,List<Department>> entry : deparmentMap.entrySet()){
            DepartmentVo departmentVo=new DepartmentVo();
            //大科室编号
            String code = entry.getKey();
            //大科室名称
            String bigname = entry.getValue().get(0).getBigname();
            departmentVo.setDepcode(code);
            departmentVo.setDepname(bigname);

            //大科室编号对应的全局数据
            List<Department> deparment1List = entry.getValue();

            //封装小科室
            List<DepartmentVo> children = new ArrayList<>();

            for (Department department : deparment1List) {
                DepartmentVo departmentVo2 =  new DepartmentVo();
                departmentVo2.setDepcode(department.getDepcode());
                departmentVo2.setDepname(department.getDepname());
                children.add(departmentVo2);
            }
            //将所有的科室放进大科室
            departmentVo.setChildren(children);
            //将当前节点(当前大科室及其下面的小科室)添加到集合
            result.add(departmentVo);
        }
        return result;
    }

    /**
     * 通过医院编号和科室编号获取科室名称
     *
     * @param hosCode
     * @param depCode
     * @return
     */
    @Override
    public String getDepName(String hosCode, String depCode) {
        Department depart = departmentRepository.getDepartmentByHoscodeAndDepcode(hosCode, depCode);

        return depart.getDepname();
    }

    /**
     * 通过医院编号和科室编号获取科室
     *
     * @param hoscode
     * @param depcode
     * @return
     */
    @Override
    public Department getDepartment(String hoscode, String depcode) {
        return departmentRepository.getDepartmentByHoscodeAndDepcode(hoscode, depcode);
    }


}
